package com.hursing.tractor.model;

import java.util.LinkedList;
import java.util.List;

import com.hursing.tractor.controller.PlayController;

public abstract class Strategy {
	// 反无主的最少牌数
	public static final int MINIMUN_COUNT_OF_FLIPPING_JOKER = 2;
	public static final int CERTAIN_TRUMP_COUNT = 6;
	
	// 底牌数
	protected static int mKittyCount;
	protected static int mMinimunMark;
	
	// 一副牌里肯定是主牌的牌数概率=6/54。6是大小王和4个主
	protected static final double mProbabilityCertainTrump = 6.0/54;
		
	// 必然是主牌的牌数期望。2副牌是2.78, 3副牌是
	protected static double mAverageCertainTrumpCount;
	// 每种花色的牌数期望。2副牌是5.56，3副牌是
	protected static double mAverageSuitCount;
	// 扣底后每人手上的牌数
	protected static double mOriginCardCount;
	
	private static Strategy mSharedInstance;
	public static Strategy instance() {
		if (mSharedInstance == null) {
			if (GameData.instance().deckCount() == 2) {
				mSharedInstance = new Strategy2();
			}
		}
		return mSharedInstance;
	}
	
	protected Strategy() {
		mKittyCount = GameData.instance().deckCount() % 2 == 0 ? 8 : 6;
		mMinimunMark = GameData.instance().deckCount() * 40;
		// 总牌数
		int total = GameData.instance().deckCount() * Card.COUNT_OF_ONE_DECK;
		// 手牌总数
		int handCardCount = total - mKittyCount;
		mOriginCardCount = handCardCount / Player.PLAYER_COUNT;
		mAverageCertainTrumpCount = mOriginCardCount * mProbabilityCertainTrump;
		mAverageSuitCount = mOriginCardCount * (1 - mProbabilityCertainTrump) / Card.COUNT_OF_ONE_SUIT;
	}
	
	public abstract void judgeWhetherFlip(Player player);
	public abstract boolean checkLegalBeforePlay(Player player, List<Card> cards, PlayController pc);
	public abstract void buryKitty(Player player);
	public abstract LinkedList<Card> playCard(Player player, PlayController pc);
	
	private final int calculateUpgrade(int origin, int grade) {
		grade = Math.abs(grade);
		int result = (origin + grade) % Card.SUIT_COUNT;
		return result;
	}
	
	public int getKittyCount() {
		return mKittyCount;
	}
	
	public final void calculateResult() {
		int grade = 3;
		GameData gameData = GameData.instance();
		if (gameData.score() > 0) {
			grade = 2 - gameData.score() / (mMinimunMark / 2);
		}

		if (grade > 0) {
			if (gameData.houseSide() == Player.SIDE_LEFT_RIGHT) {
				gameData.masterLR(calculateUpgrade(gameData.masterLR(), grade));
			} else {
				gameData.masterTB(calculateUpgrade(gameData.masterTB(), grade));
			}
			gameData.housePosition((gameData.housePosition() + 2) % Player.PLAYER_COUNT);
		} else {
			if (gameData.houseSide() == Player.SIDE_LEFT_RIGHT) {
				gameData.masterTB(calculateUpgrade(gameData.masterTB(), grade));
			} else {
				gameData.masterLR(calculateUpgrade(gameData.masterLR(), grade));
			}
			gameData.housePosition((gameData.housePosition() + 1) % Player.PLAYER_COUNT);
		}
	}
	
	public boolean checkCanBuryKitty(int selectedCount) {
		return selectedCount == mKittyCount;
	}
			
}
